<?php
/**
 * 用户权限
 * User: Administrator
 * Date: 2018\9\13 0013
 * Time: 17:58
 */

namespace app\Lib\Model\AdminAuth\Authorization;


use app\Lib\Exception\BlException;
use app\Lib\InterfaceIn\AdminAuth\Authorization\UserBindingAuthHandle;
use app\Lib\InterfaceIn\AdminAuth\MenuAuthHandle;
use app\Lib\InterfaceIn\User\UserHandle;
use app\Lib\Model\AdminAuth\GetAuthorization\GetUserAuth;
use app\Lib\Model\DbModel\AdminUserPriAuth;

class UserBindingAuth extends  BindingAuthBase implements UserBindingAuthHandle
{
    /** @var UserHandle $userObj */
    private $userObj;
    private $table;
    /**
     * 初始化
     * UserBindingAuthHandle constructor.
     * @param UserHandle $userObj
     */
    public function __construct(UserHandle $userObj)
    {
        $this->userObj = $userObj;
    }

    /**
     *
     * @return array
     */
    private function getUserAuth(){
        $model  = (new GetUserAuth($this->userObj));
        $result = $model->run();
        $auth   = [];
        foreach ($result as $v){
            if($v instanceof  MenuAuthHandle){
                $auth[] = $v->getMenuId();
            }
        }
        return $auth;
    }

    /**
     * 删除旧权限
     * @param $delArray
     * @return bool
     * @throws BlException
     */
    private function delAuth($delArray){
        $model = $this->getTable();
        $map[$model->_menu_id] = ['in',$delArray];
        $result = $model->where($map)->delete();
        if(!$result){
            throw new BlException('用户私有权限删除失败');
        }
        return true;
    }

    /**
     * 新增权限
     * @param $addArray
     * @return bool
     * @throws BlException
     */
    private function addAuth($addArray){
        $model = $this->getTable();
        $data  = [];
        foreach ($addArray as $v){
            $array = [
                $model->_uid=>$this->userObj->getUid(),$model->_create_time=>time(),
                $model->_menu_id=>$v,$model->_create_uid=>$this->opUser->getUid(),$model->_status=>1
            ];
            $data[] = $array;
        }
        $result = $model->insertAll($data);
        if(!$result){
            throw new BlException('角色权限新增失败');
        }
        return true;
    }

    private function getTable(){
        if(empty($this->table)){
            $this->table = (new AdminUserPriAuth());
        }
        return $this->table;
    }
    /**
     * 执行
     * @return bool
     * @throws \app\Lib\Exception\BlException
     */
    public function run()
    {
        $auth     = $this->getAuth();
        $userAuth = $this->getUserAuth();
        $delArray = array_diff($userAuth,$auth);
        $addArray = array_diff($auth,$userAuth);
        if(!empty($delArray)){
            $this->delAuth($delArray);
        }
        if(!empty($addArray)){
            $this->addAuth($addArray);
        }
        return true;
    }

}